"""
信号量是一种更高级的线程同步机制，它可以控制同时访问共享资源的线程数量。
"""

import threading
import time

# 创建信号量对象，允许同时有2个线程访问
semaphore = threading.Semaphore(2)


def worker(id):
    print(f"Thread {id} is waiting for the semaphore.")
    # 获取信号量
    semaphore.acquire()
    try:
        print(f"Thread {id} is waiting for the semaphore.")
        time.sleep(2)  # 模拟工作
    finally:
        # 释放信号量
        semaphore.release()
        print(f"Thread {id} is waiting for the semaphore.")


threads = [threading.Thread(target=worker, args=(i,)) for i in range(3)]
for thread in threads:
    thread.start()

for thread in threads:
    thread.join()

print("All threads have finished.")
